import { useMutation, useQueryClient } from "@tanstack/react-query";

import { useApiFetch } from "@/lib/api-fetcher";
import type { CreateOutputPayload, OutputRecord } from "@/lib/types";

export function useCreateOutputMutation() {
  const fetcher = useApiFetch();
  const queryClient = useQueryClient();

  return useMutation<OutputRecord, Error, CreateOutputPayload>({
    mutationFn: async (payload) =>
      fetcher<OutputRecord, CreateOutputPayload>({
        path: "/outputs",
        method: "POST",
        body: payload,
      }),
    onSuccess: (_data, variables) => {
      queryClient.invalidateQueries({ queryKey: ["daily-outputs"] });
      queryClient.invalidateQueries({ queryKey: ["projects"] });
      queryClient.invalidateQueries({ queryKey: ["projects", variables.projectId] });
    },
  });
}
